package com.spring.theory.mvc.adapter.resolver;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.yaml.snakeyaml.Yaml;

/**
 * YmlArgumentResolver
 *
 * @author H
 * @version 1.0
 * @date 2024-01-13 16:05
 */
public class YmlReturnValueHandler implements HandlerMethodReturnValueHandler {

    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getMethodAnnotation(Yml.class) != null;
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        String str = new Yaml().dump(returnValue);
        HttpServletResponse nativeResponse = webRequest.getNativeResponse(HttpServletResponse.class);
        nativeResponse.setContentType("text/plain;charset=utf-8");
        nativeResponse.getWriter().write(str);
        //设置响应处理完成；不会走视图解析、视图渲染流程
        mavContainer.setRequestHandled(true);

    }
}
